package com.hm.gateway.filter;

import com.hm.gateway.config.AuthProperties;
import com.hm.gateway.utils.JwtTool;
import com.hmall.common.exception.UnauthorizedException;
import lombok.AllArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@AllArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {


    private final AuthProperties authProperties;

    private final JwtTool jwtTool;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request
        ServerHttpRequest request = exchange.getRequest();
        //2.判断是否需要登录验证
        if(isExclude(request.getPath().toString())){
            //放行
            return chain.filter(exchange);
        }

        //3获取token
        String token = null;
        List<String> headers = request.getHeaders().get("authorization");
        if (headers != null && !headers.isEmpty()){
            token = headers.get(0);
        }

        //4解析token
        Long userID = null;
        try {
             userID = jwtTool.parseToken(token);
        }catch (UnauthorizedException e){
            //401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //TODO 5传递用户信息
        System.out.println("用户的id："+userID);
        String userinfo = userID.toString();
//        ServerWebExchange swe = exchange.mutate()
//                .request(builder -> builder.header("user-info", userinfo))
//                .build();
        ServerHttpRequest req= exchange.getRequest().mutate().header("user-info",userinfo ).build();
        ServerWebExchange ex = exchange.mutate().request(req).build();


        System.out.println(ex.toString());
        return chain.filter(ex);
    }

    private boolean isExclude(String path) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(pathPattern,path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
